package com.huike.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huike.entity.Department;
import com.huike.entity.Role;
import com.huike.mapper.RoleMapper;
import com.huike.mapper.RolePermissionMapper;
import com.huike.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public PageInfo<Role> getPage(int currentPage, int pagesize) {
        //1.查询数据之前调PageHelper.startPage()
        PageHelper.startPage(currentPage,pagesize);
        //2.数据库查询
        List<Role> all = roleMapper.getAll();
        //3.将查询的结果放到PageInfo里
        return new PageInfo<>(all);
    }

    @Override
    public Role getRoleById(Long id) {
        return roleMapper.getRoleById(id);
    }

//    @Override
//    public int deleteRole(Integer id) {
//        return roleMapper.deleteRole(id);
//    }

    @Override
    public List<Role> getAll() {
        return roleMapper.getAll();
    }

    @Override
    @Transactional
    public void saveOrUpdate(Role role,Long[] permissionIds) {
        //1.先得到角色id
        roleMapper.insert(role);
        Long roleId = role.getId();
        //2.根据角色id删除对应的所有权限
        rolePermissionMapper.deleteRelations(roleId);
        //3.插入现有权限
        if(permissionIds!=null){
            rolePermissionMapper.insertBatch(roleId,permissionIds);
        }
    }

    @Override
    @Transactional
    public void delete(Long id){
        roleMapper.deleteById(id);
        //还需删除关联关系
        rolePermissionMapper.deleteRelations(id);
    }
}
